# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class EquipmentSparePart(Document):
    def validate(self):
        """验证数据"""
        # 从ERPNext Item获取物料信息
        if self.item_code:
            item = frappe.get_doc("Item", self.item_code)
            self.item_name = item.item_name
            
            # 获取当前库存
            from erpnext.stock.utils import get_stock_balance
            self.current_stock = get_stock_balance(self.item_code, self.storage_location)
            
            # 获取最近采购价
            last_purchase = frappe.get_all("Purchase Invoice Item",
                filters={"item_code": self.item_code},
                fields=["rate"],
                order_by="creation desc",
                limit=1
            )
            if last_purchase:
                self.last_purchase_rate = last_purchase[0].rate

        # 检查库存水平
        if self.current_stock and self.current_stock < self.min_stock_level:
            frappe.msgprint(f"备件 {self.item_name} 库存不足，当前库存：{self.current_stock}，最低库存：{self.min_stock_level}")

    def update_consumption(self, qty, maintenance_request=None):
        """更新消耗记录"""
        self.total_consumed = (self.total_consumed or 0) + qty
        self.last_consumption_date = frappe.utils.today()
        self.save()
        
        # 检查是否需要采购提醒
        if self.current_stock <= self.reorder_level:
            self.create_purchase_reminder()

    def create_purchase_reminder(self):
        """创建采购提醒"""
        # 发送库存预警通知
        frappe.publish_realtime(
            event="spare_part_reorder",
            message={
                "item_name": self.item_name,
                "current_stock": self.current_stock,
                "reorder_level": self.reorder_level,
                "equipment": self.equipment
            },
            user="Equipment Manager"
        )